package xyz.jcat.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import xyz.jcat.common.exception.ConvertException;

import java.io.IOException;
import java.util.List;

/**
 * @author shixd
 * @date 2018-03-28 15:58:55
 */
public class JsonUtils {

    private static ObjectMapper OM;

    /**
     * 对象转json字符串
     *
     * @param obj
     * @return
     */
    public static String toString(Object obj) {
        try {
            if (ObjectUtils.isNull(obj))
                return null;
            return OM.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new ConvertException("对象转json字符串异常", e);
        }
    }

    /**
     * json字符串转java对象
     *
     * @param json
     * @param clazz
     * @param <V>
     * @return
     */
    public static <V> V parseObject(String json, Class<V> clazz) {
        try {
            return OM.readValue(json, clazz);
        } catch (IOException e) {
            throw new ConvertException("解析json对象异常", e);
        }
    }

    public static <V> List<V> parseList(String json, Class<V> clazz) {
        try {
            return OM.readValue(json, new TypeReference<List<V>>() {});
        } catch (IOException e) {
            throw new ConvertException("解析json集合对象异常", e);
        }
    }

    public static <V> V parseObject(Object jsonObject, Class<V> clazz) {
        try {
            return OM.convertValue(jsonObject, clazz);
        } catch (IllegalArgumentException e) {
            throw new ConvertException("解析json对象异常", e);
        }
    }

    public static <V> List<V> parseList(Object jsonObject, Class<V> clazz) {
        try {
            return OM.convertValue(jsonObject, new TypeReference<List<V>>() {});
        } catch (IllegalArgumentException e) {
            throw new ConvertException("解析json对象异常", e);
        }
    }

    static {
        OM = new ObjectMapper();
        OM.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }
}
